﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Streambolics
{
    /// <summary>
    ///     A computing module that is regularly polled.
    /// </summary>

    public abstract class PolledComputingModule : ComputingModule
    {
        private TimeSpan _Delay = 5.Seconds ();
        private DateTime _Next;

        public TimeSpan Delay
        {
            get
            {
                return _Delay;
            }
            protected set
            {
                _Delay = value;
            }
        }

        public DateTime NextExecution
        {
            get
            {
                return _Next;
            }
        }

        public static void PollChildrenOf (ComputingModule aParent)
        {
            foreach (PolledComputingModule m in aParent.GetChildren<PolledComputingModule> ())
            {
                m.Poll ();
            }
        }

        public static void PollAll ()
        {
            PollChildrenOf (MasterComputingModule.MasterModule);
        }

        protected abstract void DoPoll ();

        public void Poll ()
        {
            if (IsRunning)
            {
                if (DateTime.Now > _Next)
                {
                    _Next = DateTime.Now + _Delay;
                    try
                    {
                        DoPoll ();
                    }
                    catch (Exception ex)
                    {
                        DeclareFailed (ex);
                    }
                }
            }
        }
    }
}
